<template>
  <div class="add-dish">
    <el-form :model="ruleForm" :rules="rules" ref="rulesForm">
      <div class="name-category">
        <el-form-item prop="dishName" label="菜品名称：">
          <el-input v-model="ruleForm.dishName" placeholder="请填写菜品名称"></el-input>
        </el-form-item>
        <el-form-item prop="dishCategoryId" label="菜品分类：">
          <el-select v-model="ruleForm.dishCategoryId" placeholder="请选择菜品分类">
            <el-option
             v-for="item in dishCategoryOptions" :key="item.value"
             :value="item.value"
             :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="price">
        <el-form-item prop="price" label="菜品价格：">
          <el-input v-model="ruleForm.price" placeholder="请设置菜品价格"></el-input>
        </el-form-item>
      </div>
      <div class="flavor">
        <el-form-item label="口味做法配置：">
          <el-button v-if="isAddFlavor === false" type="primary" @click="openAddFlavor">+ 添加口味</el-button>
          <div v-else class="add-flavor">
            <div class="title">
              <span>口味名（3个字内）</span>
            </div>
            <div class="main">
              <div class="flavor-list">
                <div v-for="(item, key) in flavorDetailsList" :key="item.key" class="flavor-item">
                  <FlavorSelect :residueDishFlavor="residueDishFlavor" :flavorOptions="flavorOptions" :flavorName="item.label" :key="key" @change="handleFlavorSelect($event, key)"></FlavorSelect>
                  <div class="flavor-details">
                    <div v-for="(detailsItem, detailsKey) in item.details" :key="detailsKey" class="details-item">
                      <span>{{ detailsItem.label }}</span>
                      <span @click="handleDeleteFlavorValue(key, detailsKey)">X</span>
                    </div>
                  </div>
                  <span class="delete" @click="handleDeleteFlavor(key)">删除</span>
                </div>
              </div>
            </div>
            <el-button v-show="flavorDetailsList.length !== 4" type="primary" @click="addFlavor">添加口味</el-button>
          </div>
        </el-form-item>
      </div>
      <div class="pic">
        <el-form-item prop="uploadPicUrl" label="菜品图片">
            <FileUpload @change="handleUploadSuccess" @click="deleteImg" :uploadPicUrl="ruleForm.uploadPicUrl" :headers="headers"></FileUpload>
        </el-form-item>
      </div>
      <div class="desciprtion">
        <el-form-item label="菜品描述">
          <el-input v-model="description" rows="3" type="textarea" placeholder="菜品描述，最长200字"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <hr />
    <div class="operate">
      <el-button @click="$router.back()" class="cancel">取消</el-button>
      <el-button @click="handleEditSave" class="save">保存</el-button>
      <el-button v-show="!isEditStatus" @click="handleSave(false)" class="save">保存</el-button>
      <el-button v-show="!isEditStatus" @click="handleSave(true)" type="primary">保存并继续添加</el-button>
    </div>
  </div>
</template>

<script>
import { addDish, editDish, getIdDish } from '@/api/dish'
import { getCategoryList } from '@/api/category'
import FlavorSelect from '@/views/dish/components/FlavorSelect.vue'
import { getToken } from '@/utils/storage'
import FileUpload from '@/components/FileUpload.vue'
export default {
  name: 'AddDish',
  data () {
    const validateDishName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入菜品名称'))
      }

      const reg = /^[\u4e00-\u9fa5A-Za-z0-9]{2,20}$/
      if (!reg.test(value)) {
        callback(new Error('菜品名称输入不符，请输入2-20个字符'))
      }
      callback()
    }
    const validatePrice = (rule, value, callback) => {
      const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/
      if (!reg.test(value)) {
        callback(new Error('菜品价格格式有误，请输入大于零且最多保留两位小数的金额'))
      }
      callback()
    }
    const validateUploadPicUrl = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('菜品图片不能为空'))
      }
      callback()
    }
    return {
      dishCategoryOptions: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 验证数据
      ruleForm: {
        dishName: '',
        dishCategoryId: '',
        price: '',
        uploadPicUrl: ''
      },
      description: '',
      // 验证规则
      rules: {
        dishName: [
          { validator: validateDishName, required: true, trigger: 'blur' }
        ],
        dishCategoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { validator: validatePrice, required: true, trigger: 'blur' }
        ],
        uploadPicUrl: [
          { validator: validateUploadPicUrl, required: true, trigger: 'blur' }
        ]
      },
      isAddFlavor: false,
      flavorOptions: [
        {
          value: 1,
          label: '甜度',
          details: [
            { label: '无糖' },
            { label: '少糖' },
            { label: '半糖' },
            { label: '多糖' },
            { label: '全糖' }
          ]
        },
        {
          value: 2,
          label: '温度',
          details: [
            { label: '热饮' },
            { label: '常温' },
            { label: '去冰' },
            { label: '少冰' },
            { label: '多冰' }
          ]
        },
        {
          value: 3,
          label: '忌口',
          details: [
            { label: '不要葱' },
            { label: '不要蒜' },
            { label: '不要香菜' },
            { label: '不要辣' }
          ]
        },
        {
          value: 4,
          label: '辣度',
          details: [
            { label: '不辣' },
            { label: '微辣' },
            { label: '中辣' },
            { label: '重辣' }
          ]
        }
      ], // 原始口味数据
      flavorDetailsList: [], // 待上传口味数据
      residueDishFlavor: [], // 剩余的选择框口味数据
      isEditStatus: false, // 是否是编辑状态
      status: ''
    }
  },
  created () {
    this.getDishCategory()
    if (this.$route.query.id) {
      this.getDishDetails()
      this.isEditStatus = true
    }
  },
  methods: {
    deleteImg () {
      this.ruleForm.uploadPicUrl = ''
    },
    handleUploadSuccess (data) {
      this.ruleForm.uploadPicUrl = data
    },
    handleFlavorSelect (index, key) {
      const selectFlavor = this.flavorOptions[index]
      this.$set(this.flavorDetailsList, key, {
        ...selectFlavor,
        details: JSON.parse(JSON.stringify(selectFlavor.details)) || []
      })
    },
    addFlavor () {
      this.flavorDetailsList.push({ label: '', value: '', details: [] })
    },
    getResidueDishFlavor () {
      const arr = []
      this.flavorOptions.forEach(item => {
        if (this.flavorDetailsList.findIndex(item1 => item1.label === item.label) === -1) {
          arr.push(item)
        }
      })

      this.residueDishFlavor = arr
    },
    // 删除口味值
    handleDeleteFlavorValue (flavorKey, valueKey) {
      this.flavorDetailsList[flavorKey].details.splice(valueKey, 1)
    },
    // 删除口味
    handleDeleteFlavor (flavorKey) {
      this.flavorDetailsList.splice(flavorKey, 1)
    },
    // 打开添加口味框
    openAddFlavor () {
      this.isAddFlavor = true
      // 初始化
      this.flavorDetailsList.push({
        label: '',
        value: '',
        details: []
      })
    },
    // 保存
    handleSave (isContinueAdd) {
      this.$refs.rulesForm.validate(async valid => {
        if (!valid) return
        const flavors = []
        this.flavorDetailsList.forEach(item => {
          flavors.push({
            name: item.label,
            value: JSON.stringify(item.details.map(detailsItem => detailsItem.label))
          })
        })
        try {
          const res = await addDish({
            categoryId: this.ruleForm.dishCategoryId,
            description: this.description,
            flavors,
            image: this.ruleForm.uploadPicUrl,
            name: this.ruleForm.dishName,
            price: this.ruleForm.price,
            status: 0
          })
          if (res.code === 1) {
            this.$message.success('操作成功')
            this.$refs.rulesForm.resetFields()
            this.description = ''
            this.price = ''
            this.flavorDetailsList = []
            isContinueAdd || this.$router.back()
          } else {
            this.$message.error(res.msg)
          }
        } catch (error) {
          this.$message.error(error.response.data.msg)
        }
      })
    },
    // 查询菜品分类并且渲染到选择器中
    async getDishCategory () {
      const res = await getCategoryList({ type: 1 })
      if (res.code === 1) {
        res.data.forEach(item => {
          this.dishCategoryOptions.push({
            value: item.id,
            label: item.name
          })
        })
      }
    },
    // 保存编辑
    handleEditSave () {
      this.$refs.rulesForm.validate(async valid => {
        if (!valid) return
        const flavors = []
        this.flavorDetailsList.forEach(item => {
          flavors.push({
            name: item.label,
            value: JSON.stringify(item.details.map(detailsItem => detailsItem.label))
          })
        })
        try {
          const res = await editDish({
            categoryId: this.ruleForm.dishCategoryId,
            description: this.description,
            flavors,
            id: this.$route.query.id,
            image: this.ruleForm.uploadPicUrl,
            name: this.ruleForm.dishName,
            price: this.ruleForm.price
          })
          if (res.code === 1) {
            this.$message.success('操作成功')
            this.$router.back()
          } else {
            this.$message.error(res.msg)
          }
        } catch (error) {
          this.$message.error(error.response.data.msg)
        }
      })
    },
    // 获取菜品详情
    async getDishDetails () {
      const res = await getIdDish(this.$route.query.id)
      if (res.code === 1) {
        this.status = res.data.status
        this.ruleForm.dishName = res.data.name
        this.ruleForm.dishCategoryId = res.data.categoryId
        this.ruleForm.price = res.data.price
        this.ruleForm.uploadPicUrl = res.data.image
        this.description = res.data.description
        const flavors = []
        res.data.flavors.forEach((item, key) => {
          flavors.push({
            value: key + 1,
            label: item.name,
            details: JSON.parse(item.value).map(item => {
              return { label: item }
            })
          })
        })
        this.isAddFlavor = true
        this.flavorDetailsList = flavors
      }
    }
  },
  components: {
    FileUpload,
    FlavorSelect
  },
  watch: {
    // 过滤调已经选择了的口味
    flavorDetailsList () {
      if (this.flavorDetailsList.length === 0) {
        this.isAddFlavor = false
      }
      this.getResidueDishFlavor()
    }
  }
}
</script>

<style lang="less" scoped>
.add-dish {
  padding: 20px;
  border-radius: 5px;
  background-color: #fff;

  ::v-deep .el-form {
    > div {
      display: flex;

      .el-form-item {
        display: flex;

        .el-form-item__label {
          min-width: 180px;
        }

        .el-input {
          width: 350px;
        }

        .el-select .el-input {
          width: 293px;
        }

        .el-textarea {
          width: 777px;
        }
      }
    }

    .el-form-item__content {
      line-height: normal;
    }

    .flavor {
      .add-flavor {
        border: 1px solid #dfe2e8;
        background-color: #fafafb;
        border-radius: 3px;
        padding: 15px;

        .title {
          color: #606168;
        }

        .main {
          width: 100%;
          margin: 10px 0;

          .flavor-list {
            display: flex;
            flex-direction: column;
            row-gap: 10px;

            .flavor-item {
              display: flex;
              align-items: center;
              height: 40px;
              gap: 10px;
            }

            .el-select .el-input {
              width: 150px;
            }

            .flavor-details {
              display: flex;
              gap: 10px;
              min-width: 530px;
              height: 100%;
              border: 1px solid #d8dde3;
              background-color: #fff;
              padding: 5px;
              border-radius: 3px;

              .details-item {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 5px;
                color: #ffc200;
                border: 1px solid #fbe396;
                background-color: #fffbf0;
                border-radius: 4px;
                font-size: 12px;
                padding: 0 5px;

                span:last-child {
                  cursor: pointer;
                }
              }
            }

            .delete {
              color: #f56c6c;
              cursor: pointer;
            }
          }
        }
      }
    }
  }

  hr {
    margin: 20px 0;
    border: 0;
    width: 100%;
    height: 1px;
    background-color: #f3f4f7;
  }

  .operate {
    text-align: center;

    .save {
      background-color: #333;
      color: #fff;
    }

    .save:hover {
      background-color: #999;
      border-color: #999;
    }

    .save:active {
      background-color: #333;
      color: #fff;
    }
  }
}
</style>
